package com.tchcn.supermarket.ui.fragment;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fanwe.library.adapter.http.model.SDResponse;
import com.tchcn.library.http.AppRequestCallback;
import com.tchcn.library.model.BaseActModel;
import com.tchcn.library.model.UserInfoModel;
import com.tchcn.library.utils.LogUtil;
import com.tchcn.supermarket.R;
import com.tchcn.supermarket.adapter.UserPermissionAdapter;
import com.tchcn.supermarket.base.BaseRecyclerAdapter;
import com.tchcn.supermarket.base.SBaseFragment;
import com.tchcn.supermarket.common.SCommonInterface;
import com.tchcn.supermarket.model.MenuListActModel;
import com.tchcn.supermarket.model.PtActModel;
import com.tchcn.supermarket.utils.AnimationUtil;
import com.tchcn.supermarket.utils.SDToast;
import com.tchcn.supermarket.utils.ViewBinder;

import java.util.ArrayList;
import java.util.List;

/**
 *  后台管理-收银权限
 * Created by humu on 2018/10/30.
 */

public class CashPermissionFragment extends SBaseFragment {

    private LinearLayout ll_add_good_type;
    private View view_mask;
    private TextView tv_gtd_title;
    private EditText et_gt_name;

    private static CashPermissionFragment fragment;
    private CashPtAdapter ptAdapter;
    private String editPtId = "";
    private int currentCheckedUserIndex = 0;
    private String currentCheckedUserId = "";
    private TextView tv_permission_title;
    private UserPermissionAdapter permissionAdapter;

    public static CashPermissionFragment getInstance(){
        if(fragment == null){
            fragment = new CashPermissionFragment();
        }
        return fragment;
    }

    @Override
    protected int onCreateContentView() {
        return R.layout.sfragment_cash_permission;
    }

    @Override
    protected void initView() {
        initUI();
        initPsTypes();
    }

    private void initPsTypes() {
        SCommonInterface.getCashPts(UserInfoModel.getUser_id(), new AppRequestCallback<PtActModel>() {
            @Override
            protected void onSuccess(SDResponse sdResponse) {
                if(actModel.isOk()){
                    PtActModel.PtData data = actModel.getData();
                    if(data != null){
                        List<PtActModel.PtData.PtModel> ptModelList = data.getRes();
                        if(ptModelList != null && ptModelList.size() > 0){
                            if(currentCheckedUserIndex < ptModelList.size()){
                                ptModelList.get(currentCheckedUserIndex).setChecked(true);
                                currentCheckedUserIndex = 0;
                                currentCheckedUserId = ptModelList.get(currentCheckedUserIndex).getId();
                                ViewBinder.setTextView(tv_permission_title,ptModelList.get(currentCheckedUserIndex).getName());
                            }
                            ptAdapter.setDatas(ptModelList);
                        }else{
                            currentCheckedUserIndex = 0;
                            currentCheckedUserId = "";
                            ptAdapter.setDatas(new ArrayList<PtActModel.PtData.PtModel>());
                        }
                    }else{
                        currentCheckedUserIndex = 0;
                        currentCheckedUserId = "";
                        ptAdapter.setDatas(new ArrayList<PtActModel.PtData.PtModel>());
                    }
                }else{
                    currentCheckedUserIndex = 0;
                    currentCheckedUserId = "";
                    ptAdapter.setDatas(new ArrayList<PtActModel.PtData.PtModel>());
                }
            }

            @Override
            protected void onFinish(SDResponse resp) {
                super.onFinish(resp);
                getPermissions();
            }
        });

    }

    private void initUI() {
        RecyclerView rv_ps = find(R.id.rv_ps);
        RecyclerView rv_ps_type = find(R.id.rv_ps_type);
        rv_ps.setLayoutManager(new GridLayoutManager(context,4));
        rv_ps_type.setLayoutManager(new LinearLayoutManager(context));
        permissionAdapter = new UserPermissionAdapter();
        permissionAdapter.setOnMenuChangedListener(new UserPermissionAdapter.OnMenuChangedListener() {
            @Override
            public void onMenuChanged(String ids) {
                LogUtil.e("setMenus",ids);
                SCommonInterface.setMenus(currentCheckedUserId, ids, new AppRequestCallback<BaseActModel>() {
                    @Override
                    protected void onSuccess(SDResponse sdResponse) {
                        if("200".equals(actModel.getCode())){

                        }
                        SDToast.showToast(context,actModel.getMsg());
                    }

                    @Override
                    protected void onFinish(SDResponse resp) {
                        super.onFinish(resp);
                        activity.updatePermissions();
                    }
                });
            }
        });
        rv_ps.setAdapter(permissionAdapter);

        ptAdapter = new CashPtAdapter();
        ptAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<PtActModel.PtData.PtModel>() {
            @Override
            public void onItemClick(View covertView, int position, PtActModel.PtData.PtModel data) {
                if(currentCheckedUserIndex >= 0 && currentCheckedUserIndex < ptAdapter.getDatas().size()){
                    ptAdapter.getItem(currentCheckedUserIndex).setChecked(false);
                }
                data.setChecked(true);
                ptAdapter.notifyDataSetChanged();
                currentCheckedUserIndex = position;
                currentCheckedUserId = data.getId();
                ViewBinder.setTextView(tv_permission_title,data.getName());
                getPermissions();
            }
        });
        rv_ps_type.setAdapter(ptAdapter);
        Button btn_new_classification = find(R.id.btn_new_classification);
        btn_new_classification.setOnClickListener(this);
        ll_add_good_type = find(R.id.ll_add_good_type);
        view_mask = find(R.id.view_mask);
        view_mask.setOnClickListener(this);
        tv_gtd_title = find(R.id.tv_gtd_title);
        et_gt_name = find(R.id.et_gt_name);
        TextView tv_gtd_cancel = find(R.id.tv_gtd_cancel);
        tv_gtd_cancel.setOnClickListener(this);
        TextView tv_gtd_confirm = find(R.id.tv_gtd_confirm);
        tv_gtd_confirm.setOnClickListener(this);
        Button btn_del_type = find(R.id.btn_del_type);
        btn_del_type.setOnClickListener(this);
        tv_permission_title = find(R.id.tv_permission_title);

    }

    private void getPermissions(){
        if(!TextUtils.isEmpty(currentCheckedUserId)){
            SCommonInterface.getMenuList(currentCheckedUserId, new AppRequestCallback<MenuListActModel>() {
                @Override
                protected void onSuccess(SDResponse sdResponse) {
                    if(actModel.isOk()){
                        MenuListActModel.MenuListData data = actModel.getData();
                        if(data != null){
                            List<MenuListActModel.MenuListData.MenuOperateModel> models = data.getRes();
                            if(models != null && models.size() > 0){
                                permissionAdapter.clearDatas();
                                permissionAdapter.setDatas(models);
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id == R.id.btn_new_classification){
            //新增
            showPtPopup("新增权限","","");
        }else if(id == R.id.btn_del_type){
            //删除
            if(TextUtils.isEmpty(currentCheckedUserId)){
                SDToast.showToast(context,"未选中");
                return;
            }
            SCommonInterface.delRole(UserInfoModel.getUser_id(), currentCheckedUserId, new AppRequestCallback<BaseActModel>() {
                @Override
                protected void onSuccess(SDResponse sdResponse) {
                    if(actModel.isOk()){
                        currentCheckedUserIndex = 0;
                        currentCheckedUserId = "";
                        initPsTypes();
                    }
                    SDToast.showToast(context,actModel.getMsg());
                }
            });
        }else if(id == R.id.view_mask){
            hidePtPopup();
        }else if(id == R.id.tv_gtd_cancel){
            hidePtPopup();
        }else if(id == R.id.tv_gtd_confirm){
            String userName = et_gt_name.getText().toString();
            if(TextUtils.isEmpty(userName)){
                SDToast.showToast(context,"请输入用户名");
                return;
            }
            if("新增权限".equals(tv_gtd_title.getText().toString())){
                SCommonInterface.addRole(UserInfoModel.getUser_id(), userName, new AppRequestCallback<BaseActModel>() {
                    @Override
                    protected void onSuccess(SDResponse sdResponse) {
                        if(actModel.isOk()){
                            initPsTypes();
                            hidePtPopup();
                        }
                        SDToast.showToast(context,actModel.getMsg());
                    }
                });
            }else if("修改权限".equals(tv_gtd_title.getText().toString())){
                SCommonInterface.updateRole(UserInfoModel.getUser_id(), editPtId, userName,
                        new AppRequestCallback<BaseActModel>() {
                            @Override
                            protected void onSuccess(SDResponse sdResponse) {
                                LogUtil.e("updateRole",sdResponse.getResult());
                                if(actModel.isOk()){
                                    initPsTypes();
                                    hidePtPopup();
                                }
                                SDToast.showToast(context,actModel.getMsg());
                            }
                        });
            }
        }
    }

    private void showPtPopup(String title, String ptId, String editContent) {
        editPtId = ptId;
        if(ll_add_good_type.getVisibility() == View.GONE){
            ll_add_good_type.startAnimation(AnimationUtil.getMaskViewAppearAnim());
            ll_add_good_type.setVisibility(View.VISIBLE);
        }
        ViewBinder.setTextView(tv_gtd_title,title);
        ViewBinder.setTextView(et_gt_name,editContent);
        showViewMask();
    }

    private void hidePtPopup(){
        if(ll_add_good_type.getVisibility() == View.VISIBLE){
            ll_add_good_type.startAnimation(AnimationUtil.getMaskViewDisappearAnim());
            ll_add_good_type.setVisibility(View.GONE);
            et_gt_name.setText("");
        }
        hideViewMask();
    }

    private void hideViewMask(){
        view_mask.startAnimation(AnimationUtil.getMaskViewDisappearAnim());
        view_mask.setVisibility(View.GONE);
    }

    private void showViewMask(){
        view_mask.startAnimation(AnimationUtil.getMaskViewAppearAnim());
        view_mask.setVisibility(View.VISIBLE);
    }

    class CashPtAdapter extends BaseRecyclerAdapter<PtActModel.PtData.PtModel>{

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.sitem_backstage_good_type;
        }

        @Override
        public void setUpData(CommonHolder holder, int position, int viewType, final PtActModel.PtData.PtModel data) {
            RelativeLayout rl_bg = getView(holder,R.id.rl_bg);
            TextView tv_type_name = getView(holder,R.id.tv_type_name);
            ViewBinder.setTextView(tv_type_name,data.getName());
            ImageView iv_edit = getView(holder,R.id.iv_edit);

            if(data.isChecked()){
                rl_bg.setBackgroundColor(context.getResources().getColor(R.color.gray_bg));
            }else{
                rl_bg.setBackgroundColor(context.getResources().getColor(R.color.white));
            }

            iv_edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPtPopup("修改权限",data.getId(),data.getName());
                }
            });

        }
    }

}
